package com.qk.mangement.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstans;
import com.qk.common.constant.ClueStatusConstans;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.clue.ClueDO;
import com.qk.dto.clue.ClueDTO;
import com.qk.dto.clue.ClueListDTO;
import com.qk.dto.clue.UpdateClueInfoDTO;
import com.qk.entity.*;
import com.qk.mangement.mapper.BusinessMapper;
import com.qk.mangement.mapper.ClueMapper;
import com.qk.mangement.mapper.ClueTrackRecordMapper;
import com.qk.mangement.mapper.UserMapper;
import com.qk.mangement.service.ClueService;
import com.qk.vo.clue.ClueVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Date:2025/10/13
 * Author:zxc
 * Description
 */
@Slf4j
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private ClueMapper clueMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;

    @Autowired
    public BusinessMapper businessMapper;

    @Override
    public PageResult<Clue> queryCluePool(ClueQueryListByPageDto clueQueryListByPageDto) {
        Page<Object> page = new Page<>(clueQueryListByPageDto.getPage(), clueQueryListByPageDto.getPageSize());
        IPage<Clue> cluePoolPage =clueMapper.queryCluePool(page, clueQueryListByPageDto);
        return PageResult.<Clue>builder().total(Long.valueOf(cluePoolPage.getTotal()).intValue()).rows(cluePoolPage.getRecords()).build();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void convertToFalse(Integer id, Integer reason, String remark) {
        Clue clue = clueMapper.selectById(id);
        clue.setStatus(ClueStatusConstans.FAKE_CLUE);
        clue.setUpdateTime(LocalDateTime.now());
        clueMapper.updateById(clue);
        ClueTrackRecord trackRecord = new ClueTrackRecord();
        BeanUtil.copyProperties(clue, trackRecord);
        trackRecord.setId(null);
        trackRecord.setClueId(clue.getId());
        trackRecord.setUserId(CurrentUserContextHolders.get());
        trackRecord.setRecord(remark);
        trackRecord.setType(0);
        trackRecord.setFalseReason(reason);
        clueTrackRecordMapper.insert(trackRecord);
    }



    @Transactional
    @Override
    public void toBusiness(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstans.CONVERT_TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);
        //将线索信息组装成生及，添加到商机表
        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setNextTime(null);
        business.setUserId(null);
        business.setStatus(BusinessStatusConstans.WAIT_ALLOCATED);
        business.setClueId(id);
        this.businessMapper.insert(business);
    }


    @Transactional
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO dto) {
        log.info("=========================Service 中 方法updateClueInfoById 处理线程名称是：{}", Thread.currentThread().getName());

        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());

        if (dto.getStatus() == ClueStatusConstans.FOLLOW_UP) {
            clue.setStatus(ClueStatusConstans.WAIT_FOLLOW_UP);
        }
        this.baseMapper.updateById(clue);
        //int i=1/0;
        // 2. 获取跟进记录信息 信息插入线索记录表 clue_track_record表
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        // 2.1 补全创建时间
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        // 2.2 将id置为 null
        clueTrackRecord.setId(null);
        // 2.3 设置当前线索跟进记录的 线索id
        clueTrackRecord.setClueId(clue.getId());
        // 2.4 设置线索跟进记录状态默认正常跟进 1正常跟进
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        // TODO 设置跟进用户id当前用户，此时当前用户的id还在拦截器中
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        // 2.4 插入数据到 clue_track_record表
        this.clueTrackRecordMapper.insert(clueTrackRecord);


    }

    @Override
    public ClueVO getClueInfoById(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        Integer userId = clue.getUserId();
        User user = userMapper.selectById(userId);

        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
                .in(ClueTrackRecord::getClueId, id)
        );
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.ClueTrackRecordVO> list = clueTrackRecords.stream().map(item -> {
            ClueVO.ClueTrackRecordVO vo = BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        clueVO.setTrackRecords(list);
        return clueVO;
    }


    private PageResult<ClueDO> clueListMp(ClueListDTO dto) {
        Page pages = new Page<>(dto.getPage(), dto.getPageSize());
        Page<ClueDO> clueDOPage = this.baseMapper.selectByPageMp(pages, dto);
        return PageResult.<ClueDO>builder()
                .total(Long.valueOf(clueDOPage.getTotal()).intValue())
                .rows(clueDOPage.getRecords())
                .build();
    }


    @Override
    public PageResult<ClueDO> clueList(ClueListDTO dto) {
//        PageHelper.startPage(dto.getPage(),dto.getPageSize());
//        List<ClueDO> list= this.baseMapper.selectByPage(dto);
//        Page<ClueDO> page=(Page<ClueDO>) list;
//        return PageResult.<ClueDO>builder()
//                .total(Long.valueOf(page.getTotal()).intValue())
//                .rows(page.getResult())
//                .build();

        return this.clueListMp(dto);
    }


    @Override
    public void addClue(ClueDTO dto) {
        if (ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getChannel())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstans.WAIT_ALLOCATED);
        this.baseMapper.insert(clue);


    }
}
